<template>
  <div class="AddOrUpdate_main add_container column_three">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="1">
        <div id="chat" class="main_main">
          <el-form ref="form" :model="formData" :rules="rules" :inline="true">
            <el-form-item label="收款单号" prop="code">
              <CodeRuleInput :band-value.sync="formData.code" table-name="finance_in_receipt" column-name="code" :is-edit="id" />
            </el-form-item>
            <el-form-item label="制单人员">
              <el-input v-model="formData.receiptByName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="制单日期">
              <el-date-picker
                v-model="formData.receiptTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :editable="false"
              />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="formData.customerName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="销售订单" prop="saleOrderCode">
              <el-input v-model="formData.saleOrderCode" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="含税总金额">
              <el-input v-model="formData.taxAllPrice" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="已开票金额">
              <el-input v-model="formData.hasReceiptPrice" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="未开票金额">
              <el-input v-model="formData.unReceiptPrice" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="已收款金额">
              <el-input v-model="formData.hasPrice" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="未收款金额">
              <el-input v-model="formData.unPrice" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="订单附件" class="double">
              <FileManageFull
                :file-names="formData.orderFileName"
                :file-real-names="formData.orderFileRealName"
                :file-urls="formData.orderUrl"
                :row-index="1"
                :readonly="true"
                @fileName="setFileName"
              />
            </el-form-item>
            <el-form-item label="附件" class="double">
              <FileManageFull
                :file-names="formData.fileName"
                :file-real-names="formData.fileRealName"
                :file-urls="formData.fileUrl"
                :row-index="1"
                @fileName="setFileName2"
              />
            </el-form-item>
            <el-form-item label="备注" class="double">
              <el-input
                v-model="formData.remark"
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入"
              />
            </el-form-item>
          </el-form>
          <div class="formItem_header">
            <!-- 订单明细 -->
            <div />
            <div class="formItem_header_operate">
              <a class="formItem_header_operate_item" @click="addRow">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteRow">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a>
            </div>
          </div>
          <div
            ref="table_container"
            class="table_container draggableTable "
          >
            <el-table
              ref="table"
              :data="listData"
              stripe
              border
              style="width: 99.9%;"
              :cell-class-name="cellClassName"
              :header-cell-class-name="headerCellClassName"
              :row-class-name="rowClassName"
              :summary-method="getSummaries"
              :show-summary="true"
              @selection-change="selectionChange"
            >
              <el-table-column width="70" type="selection" align="center" />
              <el-table-column label="状态" min-width="80" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <div v-if="scope.row.status=='2'" class="adequate_space">
                    <span>全部收款</span>
                  </div>
                  <div v-if="scope.row.status=='1'" class="under_execution">
                    <span>部分收款</span>
                  </div>
                  <div v-if="scope.row.status=='0'" class="pending_payment">
                    <span>待收款</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="开票日期" min-width="140" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.invoiceTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择"
                    :editable="false"
                    clearable
                  />
                </template>
              </el-table-column>
              <el-table-column label="发票号码" min-width="140" prop="engineeringPathCode">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.invoiceCode" placeholder="请输入" clearable />
                </template>
              </el-table-column>
              <el-table-column label="发票金额" min-width="140" prop="invoicePrice">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.invoicePrice" type="number" placeholder="请输入" clearable @input="changeInvoicePrice($event,scope.$index)" />
                </template>
              </el-table-column>
              <el-table-column
                label="附件"
                min-width="120"
              >
                <template slot-scope="scope">
                  <FileManage
                    :file-names.sync="scope.row.fileName"
                    :file-real-names.sync="scope.row.fileRealName"
                    :file-urls.sync="scope.row.fileUrl"
                    :row-index="scope.$index"
                    @fileName="setFileName3"
                  />
                </template>
              </el-table-column>
              <!--              <el-table-column label="收款时间" min-width="200" prop="inTime" :show-overflow-tooltip="true">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <el-date-picker-->
              <!--                    v-model="scope.row.inTime"-->
              <!--                    type="datetime"-->
              <!--                    value-format="yyyy-MM-dd HH:mm"-->
              <!--                    format="yyyy-MM-dd HH:mm"-->
              <!--                    placeholder="请选择"-->
              <!--                    :editable="false"-->
              <!--                  />-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column label="备注" min-width="140">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="100">
                <template slot-scope="scope">
                  <div class="blueColor" @click="payOrder(scope.row,scope.$index)">跟进收款</div>
                </template>
              </el-table-column>
              <el-table-column label="已收款" min-width="140" prop="hasPrice" />
              <el-table-column label="未收款" min-width="140" prop="unPrice" />
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="客户开票信息" name="0">
        <!--        <div-->
        <!--          ref="table_container"-->
        <!--          class="table_container draggableTable top_margin"-->
        <!--        >-->
        <!--          <el-table-->
        <!--            ref="table"-->
        <!--            :data="bankList"-->
        <!--            stripe border-->
        <!--            row-key="id"-->
        <!--            style="width: 99.9%;"-->
        <!--            :row-class-name="rowClassName"-->
        <!--          >-->
        <!--            <el-table-column label="银行账号" min-width="120" prop="bankAccount" :show-overflow-tooltip="true">-->
        <!--              <template slot-scope="scope">-->
        <!--                <span>{{ scope.row.accountNumber }}</span>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--            <el-table-column label="账户名称" min-width="100" :show-overflow-tooltip="true">-->
        <!--              <template slot-scope="scope">-->
        <!--                <span>{{ scope.row.accountName }}</span>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--            <el-table-column label="收款银行" min-width="140" prop="engineeringPathCode">-->
        <!--              <template slot-scope="scope">-->
        <!--                <span>{{ scope.row.dueBank }}</span>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--            <el-table-column label="注意事项" min-width="140" prop="engineeringPathCode">-->
        <!--              <template slot-scope="scope">-->
        <!--                <span>{{ scope.row.announcements }}</span>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--          </el-table>-->
        <!--        </div>-->
        <div class="main_main customer_info">
          <el-form :model="formData" :inline="true">
            <el-form-item label="名称">
              <el-input v-model="formData.accountName" disabled />
            </el-form-item>
            <el-form-item label="纳税人识别号">
              <el-input v-model="formData.taxpayerNumber" disabled />
            </el-form-item>
            <el-form-item label="开户行">
              <el-input v-model="formData.accountBank" disabled />
            </el-form-item>
            <el-form-item label="账号">
              <el-input v-model="formData.accountNumber" disabled />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="formData.invoicePhone" disabled />
            </el-form-item>
            <el-form-item class=" double" label="地址">
              <el-input v-model="formData.invoiceAddress" type="textarea" disabled />
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="main_bottom">
      <div>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
        <el-button @click.stop="onSubmit()">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/receivableAndPayable/receivableAndPayableManage/receipt'
import moment from 'moment'
import followPay from './trackingPayments.vue'
import Big from 'big.js'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    resData: {}
  },
  data() {
    return {
      progressTitle: '0',
      showSchedule: false,
      showSuccess: false,
      showFail: false,
      timer: undefined,
      activeName: '1',
      formData: {
        id: '',
        code: '',
        receiptByName: '',
        receiptBy: '',
        receiptTime: '',
        customerName: '',
        saleCustomerId: '',
        saleOrderId: '',
        saleOrderCode: '',
        taxAllPrice: '',
        hasReceiptPrice: '',
        unReceiptPrice: '',
        hasPrice: 0,
        unPrice: 0,
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        orderFileName: '',
        orderFileRealName: '',
        orderUrl: '',
        remark: '',
        details: []
      },
      mainId: 'id', // 表格行ID
      isSelectPurchase: '',
      tableHeight: '200',
      planIdData: [],
      ids: [],
      selectionsAll: [], // 表格所有页选中的行
      currentIndex: 0,
      listData: [],
      rules: {
        customerName: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ],
        saleOrderCode: [
          { required: true, message: '销售订单不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '收款单号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    listData: {
      handler(newVal, oldVal) {
        this.updateHasPrice(newVal)
      },
      deep: true
    },
    'formData.hasPrice'() {
      if (this.formData.hasPrice > 0) {
        this.formData.unPrice = Big(this.formData.taxAllPrice).minus(this.formData.hasPrice) < 0 ? 0 : Big(this.formData.taxAllPrice).minus(this.formData.hasPrice)
      } else {
        this.formData.unPrice = this.formData.taxAllPrice
      }
      if (this.formData.taxAllPrice == 0) {
        this.formData.unPrice = Big(Number(this.formData.hasReceiptPrice)).minus(Number(this.formData.hasPrice))
      }
    },
    'formData.hasReceiptPrice'() {
      if (this.formData.hasReceiptPrice > 0) {
        this.formData.unReceiptPrice = Big(this.formData.taxAllPrice).minus(this.formData.hasReceiptPrice) < 0 ? 0 : Big(this.formData.taxAllPrice).minus(this.formData.hasReceiptPrice)
      } else {
        this.formData.unReceiptPrice = 0
      }
      if (this.formData.taxAllPrice == 0) {
        this.formData.unPrice = Big(Number(this.formData.hasReceiptPrice)).minus(Number(this.formData.hasPrice))
      }
    },
    'formData.unPrice'() {
      if (this.formData.unPrice < 0) {
        this.formData.unPrice = 0
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.formData.receiptTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    updateHasPrice(newVal) {
      if (newVal.length > 0) {
        newVal.filter((item, index) => {
          if (this.listData[index].unPrice <= 0 && this.listData[index].hasPrice > 0) {
            this.listData[index].unPrice = 0
            this.listData[index].status = '2'
          } else if (this.listData[index].unPrice > 0 && this.listData[index].hasPrice > 0) {
            this.listData[index].status = '1'
          } else if (this.listData[index].hasPrice <= 0) {
            this.listData[index].status = '0'
          }
        })
      }
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) {
          // 单数行
          return 'fixed one'
        } else {
          // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.listData.length - 1) {
        return 'addRow'
      }
    },
    headerCellClassName(data) {
      if (['inTime'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    showDetail(data) {
      this.listData[this.currentIndex]['follows'] = data
      this.listData[this.currentIndex].hasPrice = data.map(item => item.price).reduce((accumulator, currentValue) => Number(accumulator) + Number(currentValue), 0)
      this.listData[this.currentIndex].unPrice = Number(this.listData[this.currentIndex].invoicePrice) - Number(this.listData[this.currentIndex].hasPrice)
    },
    setFileName(...data) {
      this.formData.orderFileName = data[0]
      this.formData.orderFileRealName = data[1]
      this.formData.orderUrl = data[2]
    },
    setFileName2(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    setFileName3(...data) {
      this.listData[data[3]].fileName = data[0]
      this.listData[data[3]].fileRealName = data[1]
      this.listData[data[3]].fileUrl = data[2]
    },
    addRow() {
      const obj = {
        status: '0',
        invoiceTime: '',
        invoiceCode: '',
        invoicePrice: '',
        hasPrice: '0',
        unPrice: '0',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        follows: []
      }
      this.listData.push(obj)
    },
    deleteRow() {
      this.selectionsAll.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
    },
    changeInvoicePrice(e, index) {
      this.listData[index].unPrice = Number(e) - Number(this.listData[index].hasPrice)
    },
    payOrder(row, index) {
      this.currentIndex = index
      this.$layer.iframe({// 弹框
        content: {
          content: followPay, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            row: row.follows
          }// props
        },
        area: ['880px', '350px'],
        title: '跟进收款', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    selectionChange(rows) {
      this.selectionsAll = rows
    },
    // 合计行
    getSummaries(param) {
      const {
        columns,
        data
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        switch (column.property) {
          case 'invoicePrice':
            sums[index] = data.map(item => item.invoicePrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
        switch (column.property) {
          case 'hasPrice':
            sums[index] = data.map(item => item.hasPrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.hasPrice = Number(sums[index])
            break
        }
        switch (column.property) {
          case 'unPrice':
            sums[index] = data.map(item => item.unPrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
        switch (column.property) {
          case 'invoicePrice':
            sums[index] = data.map(item => item.invoicePrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.hasReceiptPrice = Number(sums[index])
            break
        }
      })
      return sums
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.formData.receiptByName = this.formData.receiptByName ? this.formData.receiptByName : this.$store.state.user.name
        this.formData.receiptBy = this.formData.receiptBy ? this.formData.receiptBy : this.$store.state.user.userId
        this.listData = res.data.details
        this.formData.receiptTime = this.formData.receiptTime ? this.formData.receiptTime : moment(new Date()).format('YYYY-MM-DD')
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // if (this.listData.filter(item => !item.inTime).length > 0) {
          //   this.$message.warning('收款时间不能为空')
          //   return
          // }
          this.formData.details = this.listData
          this.formData.receiptTime = this.formData.receiptTime ? this.formData.receiptTime : moment(new Date()).format('YYYY-MM-DD')
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
.pending_payment {
  color: #387bfc;
}
.under_execution {
  color:#FF9900;
}
.adequate_space {
  color: #19be6b;
}
.insufficient_space {
  color: rgb(231, 108, 108);
}
.insufficient_space2 {
  color: rgb(255, 151, 32);
}
.revoke_space {
  color: #999999;
}
/deep/.blueColor{
  color: #387bfc;
}
/deep/.blueColor:hover {
    cursor: pointer;
}
.main_bottom{
  justify-content:end;
}
/deep/ .el-table__fixed-footer-wrapper {
  .el-table__cell:last-of-type {
    height: 39px !important;
  }
}
.customer_info{
  margin-top: 15px;
}
.top_margin{
  margin-top: 40px !important;
}
/deep/ .el-tabs__header{
  margin: 0 !important;
}
    ///deep/ .el-tabs__content{
    //  padding: 0 16px !important;
    //}
    .form_item{
      border-bottom: 1px solid #D6D6D6;
            // width: 100%;
      border-bottom: 1px solid #D6D6D6;
      margin-left: 0;
      margin-right: 0;
      margin-bottom: 0;
      /deep/ .el-form-item__label:before{
        content: none;
      }
      /deep/ .el-form-item__label{
        color: #1F51B3;
        font-size: 15px;
      }
      /deep/ .el-form-item__label{
        width: 140px !important;
        margin-top: 10px;
      }
      /deep/ .el-form-item__content{
        color: #333333;
        font-size: 15px;
        flex: 1;
        width: unset;
        margin-top: 10px;
        margin-right: 0px;
      }
    }
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  padding-top:20px !important ;
  height: 100%;
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
.order_header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .info_button{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
}
///deep/ .el-table__footer-wrapper{
//  width: calc(100% - 8px);
//}

//// 滚动条的宽度
///deep/ .el-table__body-wrapper::-webkit-scrollbar {
//  width: 0px; // 横向滚动条
//}
///deep/ .el-table__body-wrapper {
//
//  width: calc(100% - 8px);
//}
//
////注意:hover
///deep/ .el-table__body-wrapper:hover::-webkit-scrollbar {
//  width: 8px; // 横向滚动条
//}
///deep/ .el-table__body-wrapper:hover{
//  width: 100%;
//}

</style>
